package com.kly.controller;

import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.app.ApplicationResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kly.api.ai.model.CreateImageOutPaintingResponse;
import com.kly.common.BaseResponse;
import com.kly.common.PageRequest;
import com.kly.common.ResultUtils;
import com.kly.domain.dto.pircture.CreatePictureOutPaintingTaskRequest;
import com.kly.domain.entity.ImageExpansion;
import com.kly.exception.BusinessException;
import com.kly.exception.ErrorCode;
import com.kly.exception.ThrowUtils;
import com.kly.manager.ai.AIAppManager;
import com.kly.manager.ai.AIManager;
import com.kly.manager.auth.anno.SaSpaceCheckPermission;
import com.kly.manager.auth.model.SpaceUserPermissionConstant;
import com.kly.service.ImageExpansionService;
import com.kly.service.PictureService;
import io.reactivex.Flowable;
import io.reactivex.Scheduler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;

/**
 * @author admin
 * @date 2025/4/26
 */
@RequestMapping("/ai")
@RestController
@Slf4j
public class AIChatController {

    @Resource
    private AIManager aiManager;

    @Resource
    private AIAppManager aiAppManager;

    @Resource
    private Scheduler scheduler;

    @Resource
    private PictureService pictureService;

    @Resource
    private ImageExpansionService imageExpansionService;

    /**
     * ai助手
     */
    @GetMapping("/assistant")
    public SseEmitter aiAssistant(String prompt) {
        // 自定义线程池
        SseEmitter sseEmitter = new SseEmitter(100000L);

            Flowable<GenerationResult> flowable = aiManager.callWithMessage(prompt);
            flowable.observeOn(scheduler)
                    .doOnNext(msg -> {
                        sseEmitter.send(msg.getOutput().getChoices().get(0).getMessage().getContent());
                    }).doOnComplete(sseEmitter::complete)
                    .doOnError(e -> {
                        log.error("sse error", e);
                    }).subscribe();

        return sseEmitter;
    }


    /**
     * ai助手 app
     *
     * @param prompt
     * @return
     */
    @GetMapping("/app/assistant")
    public SseEmitter aiAppAssistant(String prompt) {
        // 自定义线程池
        SseEmitter sseEmitter = new SseEmitter(100000L);

        Flowable<ApplicationResult> flowable = null;
        try {
            flowable = aiAppManager.streamCall(prompt);
        } catch (Exception e) {
            log.info("aiAppManager.streamCall error", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        flowable.observeOn(scheduler)
                .doOnNext(msg -> {
                    sseEmitter.send(msg.getOutput().getText());
                }).doOnComplete(sseEmitter::complete)
                .doOnError(e -> {
                    log.error("error {}", e);
                })
                .subscribe();

        return sseEmitter;
    }


    @GetMapping("/rename")
    public SseEmitter aiRename(String prompt) {
        // 自定义线程池
        String systemContent = "你是一位才华横溢的诗人，擅长将普通的文字转化为充满诗意与情感的表达。请根据以下提供的内容，将其优化为更加优美且富有诗意的版本。在转化过程中，请注意以下几点：\n" +
                "\n" +
                "- 保持原文的核心信息不变，但可以适当添加细节以增强画面感或情感深度。\n" +
                "- 使用丰富的比喻、拟人等修辞手法来增添文采。\n" +
                "- 注意韵律和节奏，使文本读起来流畅悦耳。\n" +
                "- 尝试使用不同的视角或引入自然元素（如季节、天气、星辰等）作为背景或隐喻，以增加层次感。\n" +
                "\n" +
                "例如，原始文本：“今天是个好天气，我和朋友去公园散步。”\n" +
                "优化后的版本：“晴空万里，宛如画布铺展于天际。在这美好的日子里，我与友人漫步于翠绿的园林之中，仿佛置身于世外桃源。”\n" +
                "\n" +
                "现在，请对以下内容进行优化：\n" +
                "[此处插入你需要优化的具体文本]";
        SseEmitter sseEmitter = new SseEmitter(100000L);
        Flowable<GenerationResult> flowable = aiManager.callWithMessage(prompt, systemContent);
        flowable.observeOn(scheduler)
                .doOnNext(msg -> {
                    sseEmitter.send(msg.getOutput().getChoices().get(0).getMessage().getContent());
                }).doOnError(e -> {
                    log.error("sse error", e);
                }).doOnComplete(sseEmitter::complete)
                .subscribe();

        return sseEmitter;
    }


    /**
     * ai扩图
     */
    @PostMapping("/picture/expand")
    @SaSpaceCheckPermission(SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<CreateImageOutPaintingResponse> aiCreateImageOutPainting(@RequestBody CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest) {
        ThrowUtils.throwIf(createPictureOutPaintingTaskRequest == null, ErrorCode.PARAMS_ERROR);
        // 获取登录用户
        CreateImageOutPaintingResponse createImageOutPaintingResponse = pictureService.createImageOutPainting(createPictureOutPaintingTaskRequest);
        return ResultUtils.success(createImageOutPaintingResponse);
    }

    /**
     * 获取扩图列表
     */
    @PostMapping("/picture/expand/list")
    @SaSpaceCheckPermission(SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Page<ImageExpansion>> getPictureOutPaintingList(@RequestBody PageRequest pageRequest) {
        Page<ImageExpansion> imageList = pictureService.getExpandedImageList(pageRequest);
        return ResultUtils.success(imageList);
    }



}
